<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="title"
    :showCancelBtn="true" :showOkBtn="true" :canFullscreen="false" :centered="true"
    :width="800"
    wrapClassName="policy"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" :model="modelRef" autocomplete="off"></BasicForm>
  </BasicModal>
</template>

<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { FormSchema } from '/@/components/Table';
  import { saveOrUpdate, get, getTimeLimitSelect, getRateSelect } from '../Orders.api';
  import { queryDepartTreeSync, getUsersByDepartId } from '/@/api/common/api';
  import { customerSelect } from '/@/views/good/product/Product.api';
  import { policySelect } from '/@/views/good/policy/Policy.api';

  //-------定义变更参数------------------------------------
  
  // Emits声明
  const emit = defineEmits(['register', 'success']);
  //设置标题
  const title = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));

  const isUpdate = ref(true);
  // 1、部门下接
  const departOptions = ref([]);
  // 2、用户下接
  const userOptions = ref([]);
  // 3、资方产品
  const customerOptions = ref([]);
  const policyOptions   = ref([]);
  // 4、产品期数
  const policyTimeLimitOptions = ref([]);
  // 5、产品利率
  const policyRateOptions = ref([]);
  // 6、表单所有值，外部可更新
  const modelRef  = ref<any>({});

  const policyType = ref("");
  const loanDate   = ref("");
  const customerId = ref("");

  //-------------------------------------------------------

  // 7、表单数据结构
  const formSchema: FormSchema[] = [
    // TODO 主键隐藏字段，目前写死为ID
    { label: '', field: 'id', component: 'Input', show: false },
    { label: '产品编号', field: 'productCode', component: 'Input', show: false},
    { label: "资方产品", field: "customerId", component: "Input", show: false},
    { label: '期数', field: 'timeLimit', component: 'Input', show: false },
    { label: '利率', field: 'rate', component: 'Input', show: false },
    {
      label: '部门',
      field: 'region',
      component: 'Select',
      colProps: { span: 11 },
      rules: [{required: true,  message: '请选择部门'}],
    },
    {
      label: '签单员',
      field: 'soleId',
      component: 'Select',
      colProps: { span: 11 },
      rules: [{required: true,  message: '请选择签单员'}],
    },
    {
      label: '车商名称',
      field: 'dealerName',
      component: 'Input',
      componentProps: {
        placeholder: ' ',
        autoComplete: 'off'
      },
      colProps: { span: 11 },
      rules: [{required: true,  message: '请填写车商名称'}],
    },
    {
      label: '客户名字',
      field: 'customerName',
      component: 'Input',
      colProps: { span: 11 },
      rules: [{required: true,  message: '请填写客户名字'}],
      componentProps: {
        placeholder: ' ',
        autoComplete: 'off'
      },
    },
    {
      label: '融资总额',
      field: 'amountTotal',
      component: 'InputNumber',
      colProps: { span: 11 },
      rules: [{required: true,  message: '请填写融资总额'}],
    },
    {
      label: '放款日期',
      field: 'loanDate',
      component: 'DatePicker',
      colProps: { span: 11 },
      rules: [{required: true,  message: '请填写放款日期'}],
      componentProps: ({ formModel }) => {
        return {
          //日期格式化，页面上显示的值
          format: 'YYYY-MM-DD',
          //返回值格式化（绑定值的格式）
          valueFormat: 'YYYY-MM-DD',
          placeholder: '',
          onChange: (e) => {
            console.info("loanDate@@@@", e);
            //formModel.cId = []
            formModel.timeLimit = ''
            formModel.rate = ''
            formModel.gps = ''
            formModel.rate = ''
            formModel.extraCharge = ''
            loanDate.value = e
            getPolicyOptions(formModel.cId);
          }
        }
      },
    },
    {
      label: '政策类型',
      field: 'policyType',
      colProps: { span: 11 },
      component: 'JDictSelectTag',
      defaultValue: '3',
      componentProps: ({ formModel }) => {
        return {
          dictCode: 'policyType',
          placeholder: '',
          exclusive: '1',
          stringToNumber: false,
          onSelect: (e) => {
            if (modelRef.value['policyType'] == e) {
              formModel.cId = modelRef.value['cId']
            } else {
              formModel.cId = []
              formModel.timeLimit = ''
              formModel.rate = ''
              formModel.gps = ''
              formModel.rate = ''
              formModel.extraCharge = ''
              policyType.value = e;
              policyTimeLimitOptions.value = []
              policyRateOptions.value = []
            }
          }
        }
      },
      dynamicDisabled: true,
      rules: [{required: true,  message: '请选择政策'}],
    },
    {
      label: '资方产品',
      field: 'cId',
      component: 'Cascader',
      componentProps: {
        getPopupContainer: () => document.body,
        placeholder: '请输入',
      },
      dynamicDisabled: ({ values }) => {
        //console.info("dynamicDisabled@@cId", values)
        policyType.value = values.policyType
        loanDate.value   = values.loanDate
        return !values.policyType || !values.loanDate;
      },
      dynamicRules: ({ model }) => {
        return [
          { required: true, message: '资方产品不能为空！' },
          { validator: (_, value) => {
            return new Promise((resolve, reject) => {
              if (!value) {
                return resolve() //不与required重复
              } 
              let len = value.length;
              if ( len > 1) {
                model.customerId = value[len - 1]
                customerId.value = value[len - 1]
                //console.info("dynamicRules", value, value[len - 1], model.customerId)
                return resolve()
              } else {
                model.customerId = ''
                customerId.value = ''
                return reject('选择的资方产品不对，请重新选择！');
              }
            });
            },
          },
        ]
      },
      colProps: {
        span: 11,
      },
    },
    {
      label: '商务政策',
      field: 'pId',
      component: 'Cascader',
      componentProps: {
        getPopupContainer: () => document.body,
        placeholder: '请输入',
      },
      dynamicDisabled: ({ values }) => {
        policyType.value = values.policyType
        return !values.policyType || !values.loanDate;
      },
      dynamicRules: ({ model }) => {
        return [
          { required: true, message: '商务政策不能为空！' },
          { validator: (_, value) => {
            return new Promise((resolve, reject) => {
              if (!value) {
                return resolve() //不与required重复 [len - 1]
              } 
              let len = value.length;       
              if ( len > 1) {
                model.timeLimit = value[0]
                model.rate = value[1]
                //customerId.value = value[len - 1]
                //console.info("dynamicRules", value, value[len - 1], model.customerId)
                return resolve()
              } else {
                model.timeLimit = ''
                model.rate = ''
                //customerId.value = ''
                return reject('选择的商务政策不对，请重新选择！');
              }
            });
            },
          },
        ]
      },
      colProps: {
        span: 11,
      },
    },
    {
      label: '附加费',
      field: 'extraCharge',
      component: 'Input',
      colProps: { span: 11 }
    },
    {
      label: 'GPS费用',
      field: 'gpsCost',
      component: 'InputNumber',
      colProps: { span: 11 },
    },
    {
      label: '返利系数',
      field: 'rebateRatio',
      component: 'InputNumber',
      colProps: { span: 11 },
      componentProps: {
        step: "0.1",
        max: "20",
        addonAfter: "%",
      },
    },
    {
      label: '车商返利',
      field: 'dealerRebate',
      component: 'InputNumber',
      colProps: { span: 11 },
    },
    {
      label: '备注',
      field: 'remarks',
      component: 'Input',
      colProps: { span: 11 },
    },

  ];

  // 表单配置
  const [registerForm, { resetFields, validate, updateSchema, clearValidate }] = useForm({
    labelWidth: 100,
    schemas: formSchema,
    showActionButtonGroup: false,
  });

  //表单赋值
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    //重置表单
    await resetFields();
    setModalProps({ confirmLoading: false, showCancelBtn: data?.showFooter, showOkBtn: data?.showFooter });
    isUpdate.value = !!data?.isUpdate;
    modelRef.value = {};
    
    // 1、部门下接数据 queryDepartTreeSync({ pid: '98608507967900000' });
    departOptions.value = await queryDepartTreeSync({ pid: '1798608507967900000' });
    // 2、用户下接数据
    userOptions.value = [];
    // 3、资方产品
    customerOptions.value = await customerSelect();
    // 4、产品期数
    policyTimeLimitOptions.value = [];
    // 5、产品利率
    policyRateOptions.value = []
    // 6、当前值，当前界面使用
    policyType.value = '';
    loanDate.value = '';
    customerId.value = '';

    updateSchema([
      {
        field: 'region',
        componentProps: {
          options: departOptions,
          onChange: (e) => getUserOptions(e),
        },
      },
      {
        field: "cId",
        componentProps: { 
          options: customerOptions,
          onChange: (e) => getPolicyOptions(e),
        },
      },
    ]);

    //是更新操作 - 表单加载数据
    if (unref(isUpdate)) {
      // 1、获取订单数据
      const order = await get({ id: data.record.id });
      if (!order) {
        alert('订单信息查询错误，无法编辑！');
        return;
      }

      data.record = order;
      //modelRef.value = order; // 这个可以赋值表单
      policyType.value = order.policyType;
      loanDate.value   = order.loanDate;
      customerId.value = order.customerId;
      // 隐藏底部时禁用整个表单
      //setProps({ disabled: !showFooter });

      // 2、加载 - 接单员数据
      getUserOptions(order.region)

      // 3、加载 - 资方产品
      const customerPath = data.record.customerPath && data.record.customerPath.split(',');
      const arrays = customerPath <= 0 ? "" : customerPath.filter((item) => item); //[366,381,382]//e
      //console.info(coopPath, arrays)
      data.record.cId = arrays;
      
      // 4、加载 - 期限利率
      getPolicyOptions(arrays)
      data.record.pId = [String(data.record.timeLimit), String(data.record.rate.toFixed(2))];
      //getPolicyTimeLimitOptions(arrays);
      //getPolicyRateOptions(order.timeLimit);
      
    }

    // 无论新增还是编辑，都可以设置表单值
    if (typeof data.record === 'object') {
      // setFieldsValue({
      //   ...data.record,
      // });
      modelRef.value = data.record;
    }

    await clearValidate();
  });

  /**************************************************************************
   * 下接操作事件
   */

  // 接单员
  async function getUserOptions(value) {
    if (!value) {
      return
    }
    userOptions.value = await getUsersByDepartId({ id: value });
    updateSchema([{ 
      field: 'soleId', 
      componentProps: { 
        options: userOptions
      }}
    ]);
  }

  async function getPolicyOptions(arrays) {
    if (!arrays) {
      return
    }

    let len = arrays.length;
    if ( len > 1) {
      let params = {customerId: arrays[len - 1], loanDate: loanDate.value}
      await policySelect(params).then(res => {
        //console.info("getPolicyOptions@@", res)
        policyOptions.value = []
        if (res && res.length > 0) {
          policyOptions.value = res
        }
      });
      updateSchema([{ 
        field: 'pId', 
        componentProps: { 
          options: policyOptions,
        }}
      ]);
    }
  }

  //表单提交事件
  async function handleSubmit() {
    try {
      let values = await validate();
      setModalProps({ confirmLoading: true });
      //提交表单
      await saveOrUpdate(values, isUpdate.value);
      //关闭弹窗
      closeModal();
      //刷新列表
      emit('success', { isUpdate: isUpdate.value, values });
    } catch (error) {
      console.warn(error);
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }


</script>

<style lang="less" scoped>

:deep(.css-dev-only-do-not-override-udyjmm).ant-divider-horizontal {
  margin: 0;
}

</style>
